package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName $ {NAME}
 * @Description TODO
 * @Author 寇铭
 * @Date 2022/6/17 10:47
 * @Version 1.0
 **/
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据:{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }


    /**
     * 订单查询
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime) {

        log.info("开始时间:{}", beginTime);//开始时间:2022-06-01 00:00:00
        log.info("结束时间:{}", endTime);//结束时间:2022-07-01 23:59:59

        /*
        将String类型的时间转换为LocalDateTime
         */
        LocalDateTime parseBeginTime = null;
        LocalDateTime parseEndTime = null;
        if (beginTime != null && endTime != null) {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            parseBeginTime = LocalDateTime.parse(beginTime, df);
            parseEndTime = LocalDateTime.parse(endTime, df);
        }


        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> dtoPage = new Page<>();

        //根据id和时间查询
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(number != null, Orders::getNumber, number);
        queryWrapper.lt(parseEndTime != null, Orders::getCheckoutTime, parseEndTime).gt(parseBeginTime != null, Orders::getCheckoutTime, parseBeginTime);
        orderService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<Orders> ordersList = pageInfo.getRecords();
        //把地址和下单用户名设置进orderDto中
        List<OrderDto> list = ordersList.stream().map(item -> {
            OrderDto orderDto = new OrderDto();
            //拷贝
            BeanUtils.copyProperties(item, orderDto);
            Long addressBookId = item.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            orderDto.setAddress(addressBook.getDetail());
            orderDto.setUserName(addressBook.getConsignee());

            return orderDto;

        }).collect(Collectors.toList());

        //设置orderDto的records
        dtoPage.setRecords(list);

        return R.success(dtoPage);
    }


    /**
     * 用户页面订单查询
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){

        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderDto> dtoPage = new Page<>();
        //当前用户id
        Long currentId = BaseContext.getCurrentId();
        //根据当前用户的id查询订单信息
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, currentId);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        orderService.page(pageInfo,queryWrapper);
        //拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        List<Orders> list = pageInfo.getRecords();

        List<OrderDto> orderDtoList = list.stream().map(item -> {

            OrderDto orderDto = new OrderDto();
            //拷贝
            BeanUtils.copyProperties(item, orderDto);
            //根据订单id查询订单明细
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(wrapper);
            orderDto.setOrderDetails(orderDetails);
            return orderDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(orderDtoList);

        return R.success(dtoPage);

    }

    /**
     * 修改订单状态
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders order){
        log.info("status:{}", order.getStatus());
        log.info("id:{}", order.getId());
        orderService.updateById(order);
        return R.success("订单状态修改成功！");
    }



}
